//
//  StringExtension.swift
//  Lottery
//
//  Created by 薛永伟 on 2019/1/16.
//  Copyright © 2019年 薛永伟. All rights reserved.
//

import Foundation

extension String{
    
    struct FilterPicker{
        static let Chinese = "[^\\u4e00-\\u9fa5]"
        static let password = "^[a-zA-Z0-9]{6,20}+$"
    }
    
    /// 过滤出符合条件的字符
    func filterPickCharactor(withRegex:String) -> String{
        var result = self
        do {
            let regex = try NSRegularExpression.init(pattern: withRegex, options: NSRegularExpression.Options.caseInsensitive)
            result = regex.stringByReplacingMatches(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, result.count), withTemplate: "")
        } catch  {
            YRLog("过滤出错:\(error.localizedDescription)", type: .error)
        }
        return result
    }
    
    
}

//MARK: - --------------字符串处理--------------
extension String {
    
    /// 获取包含的URL数组
    func getIncludedUrls() -> [String] {
        
        let regulaStr = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
        var result = [String]()
        do{
            let regex = try NSRegularExpression.init(pattern: regulaStr, options: .caseInsensitive)
            let arrayOfAllMatches = regex.matches(in: self, options: [], range: NSRange.init(location: 0, length: self.count))
            for match in arrayOfAllMatches {
                let nsstr = self as NSString
                let substringForMatch = nsstr.substring(with: match.range)
                result.append(substringForMatch)
            }
        }catch {
            YRLog(error.localizedDescription, type: .error)
        }
        
        return result
    }
    
}

//MARK: - --------------解编码--------------
extension String {
    
    /// 讲qury(name="中国")编码之后的字符串
    var urlQuryEncode:String {
        
        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
            .urlQueryAllowed)
        
        return encodeUrlString ?? self
    }
    
    /// 讲quryj解编码之后的字符串
    var urlQuryDecode:String {
        
        return self.removingPercentEncoding ?? self
    }
}
